//
//  UFOHeroTimePlayPageView.m
//  unrivalledForUniverse
//
//  Created by dllo on 16/1/15.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "UFOHeroTimePlayPageView.h"
#import <AVFoundation/AVFoundation.h>

@interface UFOHeroTimePlayPageView ()
@property (nonatomic, retain) AVPlayerLayer *playerLayer; // 播放层
@property (nonatomic, retain) UIView *container; // 播放器容器
@property (nonatomic, retain) UIButton *playOrPauseB; // 播放/暂停
@property (nonatomic, retain) UISlider *proSlider; // 播放进度
@property (nonatomic, retain) UILabel *timeL; // 时间label
@property (nonatomic, retain) UIView *controlV; // 功能控制面板
@property (nonatomic, retain) UIButton *fullB; // 全屏
@property (nonatomic, retain) UIProgressView *progressV; // 缓冲进度条
@end
@implementation UFOHeroTimePlayPageView

- (void)dealloc
{
    [self removeObserverFromPlayerItem:self.player.currentItem];
    [self removeNotification];
    
    [_playerLayer release];
    [_progressV release];
    [_fullB release];
    [_timeL release];
    [_controlV release];
    [_player release];
    [_container release];
    [_playOrPauseB release];
    [_proSlider release];
    [_urlArr release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubviews];
    }
    return self;
}

// 创建视图
- (void)createSubviews
{
    self.backgroundColor = [UIColor blackColor];
    self.userInteractionEnabled = YES;
    // 创建播放器容器
    self.container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENWIDTH * 3 / 5)];
    self.container.center = self.center;
    self.container.center = self.center;
    self.container.userInteractionEnabled = YES;
    self.container.backgroundColor = [UIColor clearColor];
    [self addSubview:self.container];
    [_container release];
    
    // 轻拍
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.container addGestureRecognizer:tapGR];
    [tapGR release];
    
    // 控制面板
    self.controlV = [UIView new];
    self.controlV.userInteractionEnabled = YES;
    self.controlV.backgroundColor = [UIColor colorWithWhite:0.502 alpha:1.000];
    [self addSubview:self.controlV];
    
    
    [self.controlV mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.mas_bottom).offset(- 60 * SCREENHEIGHT / HEIGHTSIXP);
        make.height.equalTo(@(60 * SCREENHEIGHT / HEIGHTSIXP));
        make.width.equalTo(self);
        
    }];
    
    // 播放按钮
    self.playOrPauseB = [UIButton new];
    self.playOrPauseB.frame = CGRectMake(10 * SCREENWIDTH / WIDTHSIXP, 10 * SCREENHEIGHT / HEIGHTSIXP, 40 * SCREENWIDTH / WIDTHSIXP, 40 * SCREENHEIGHT / HEIGHTSIXP);
    [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_play_hover.tiff"] forState:UIControlStateNormal];
    [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_play_down.tiff"] forState:UIControlStateHighlighted];
    [self.playOrPauseB addTarget:self action:@selector(playOrPauseAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlV addSubview:self.playOrPauseB];
    
    [self.playOrPauseB mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.equalTo(self.controlV).offset(10 * SCREENWIDTH / WIDTHSIXP);
        make.top.equalTo(self.controlV).offset(10 * SCREENHEIGHT / HEIGHTSIXP);
        make.width.equalTo(@(40 * SCREENWIDTH / WIDTHSIXP));
        make.height.equalTo(@(40 * SCREENHEIGHT / HEIGHTSIXP));
        
    }];
    
    // 缓冲条
    self.progressV = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressV.trackTintColor = [UIColor whiteColor];
    self.progressV.userInteractionEnabled = YES;
    self.progressV.progressTintColor = [UIColor lightGrayColor];
    [self.controlV addSubview:self.progressV];
    [_progressV release];
    
    [self.progressV mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.equalTo(self.controlV).offset(60 * SCREENWIDTH / WIDTHSIXP);
        make.top.equalTo(self.controlV).offset(45 * SCREENHEIGHT / HEIGHTSIXP);
        make.right.equalTo(self.controlV).offset(- 20 * SCREENWIDTH / WIDTHSIXP);
        make.height.equalTo(@(1 * SCREENHEIGHT / HEIGHTSIXP));
        
    }];
    
    // 进度条
    self.proSlider = [UISlider new];
    [self.proSlider setThumbImage:[UIImage imageNamed:@"progress_sliderblock"] forState:UIControlStateNormal];
    self.proSlider.maximumValue = 1;
    self.proSlider.minimumValue = 0;
    self.proSlider.maximumTrackTintColor = [UIColor clearColor];
    [self.proSlider addTarget:self action:@selector(proAction:) forControlEvents:UIControlEventValueChanged];
    [self.controlV addSubview:self.proSlider];
    
    [self.proSlider mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.equalTo(self.controlV).offset(60 * SCREENWIDTH / WIDTHSIXP);
        make.top.equalTo(self.controlV).offset(40 * SCREENHEIGHT / HEIGHTSIXP);
        make.right.equalTo(self.controlV).offset(- 20 * SCREENWIDTH / WIDTHSIXP);
        make.height.equalTo(@(10 * SCREENHEIGHT / HEIGHTSIXP));
        
    }];
    
    // 时间label
    self.timeL = [UILabel new];
    self.timeL.text = @"00:00";
    self.timeL.font = [UIFont systemFontOfSize:12.0 * SCREENHEIGHT / HEIGHTSIXP];
    [self.controlV addSubview:self.timeL];
    
    [self.timeL mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.equalTo(self.progressV);
        make.top.equalTo(self.controlV).offset(20 * SCREENHEIGHT / HEIGHTSIXP);
        make.width.equalTo(@(60 * SCREENWIDTH / WIDTHSIXP));
        make.height.equalTo(@(20 * SCREENHEIGHT / HEIGHTSIXP));
        
    }];

    // 全屏
    self.fullB = [UIButton new];
    [self.fullB setImage:[UIImage imageNamed:@"iconfont-icon-2"] forState:UIControlStateNormal];
    [self.fullB addTarget:self action:@selector(fullScreenAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlV addSubview:self.fullB];
    
    [self.fullB mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.equalTo(self.controlV.mas_right).offset(- 30 * SCREENWIDTH / WIDTHSIXP);
        make.right.equalTo(self.controlV).offset(- 10 * SCREENWIDTH / WIDTHSIXP);
        make.top.equalTo(self.controlV).offset(10 * SCREENHEIGHT / HEIGHTSIXP);
        make.height.equalTo(@(20 * SCREENHEIGHT / HEIGHTSIXP));
        
    }];
}

// 全屏
- (void)fullScreenAction:(UIButton *)sender
{
    if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
        self.frame = CGRectMake(0, 0, SCREENHEIGHT, SCREENWIDTH);
        self.container.frame = CGRectMake(0, 0, SCREENHEIGHT, SCREENHEIGHT * 3 / 5);
        self.container.center = self.center;
        self.playerLayer.frame = self.container.bounds;
        
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    } else {
        self.frame = CGRectMake(0, 0, SCREENHEIGHT, SCREENWIDTH);
        
        self.container.frame = CGRectMake(0, 0, SCREENHEIGHT, SCREENWIDTH);
        
        self.playerLayer.frame = self.container.bounds;

        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    }
}

// 轻拍
- (void)tapAction
{
    if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
        
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.controlV.frame;
            if (SCREENHEIGHT == frame.origin.y) {
                
                frame.origin.y = SCREENHEIGHT - 60 * SCREENHEIGHT / WIDTHSIXP;
                self.controlV.frame = frame;
                
                [self.delegate hiddenNavigationBarWithPara:NO];
            } else {
                
                frame.origin.y = SCREENHEIGHT;
                self.controlV.frame = frame;
                
                [self.delegate hiddenNavigationBarWithPara:YES];
            }
        }];
 
    } else {
       
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.controlV.frame;
            if (SCREENHEIGHT == frame.origin.y) {
                
                frame.origin.y = SCREENHEIGHT - 60 * SCREENHEIGHT / HEIGHTSIXP;
                self.controlV.frame = frame;
                
                [self.delegate hiddenNavigationBarWithPara:NO];
                
            } else {
                
                frame.origin.y = SCREENHEIGHT;
                self.controlV.frame = frame;
                
                [self.delegate hiddenNavigationBarWithPara:YES];
            }
        }];
    }

   
}

// 进度条
- (void)proAction:(UISlider *)sender
{
    // 关联视频进度
    [self.player seekToTime:CMTimeMakeWithSeconds(sender.value * CMTimeGetSeconds(self.player.currentItem.duration), 1)];
    [self.player play];
}

// 播放/暂停
- (void)playOrPauseAction:(UIButton *)sender
{
    // 判断播放状态 rate = 0 -> 暂停  1 -> 播放
    if (1 == self.player.rate) {
        [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_play_hover.tiff"] forState:UIControlStateNormal];
        [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_play_hover.tiff"] forState:UIControlStateHighlighted];
        [self.player pause];
    } else if (0 == self.player.rate) {
        [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_pause_hover.tiff"] forState:UIControlStateNormal];
        [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_pause_down.tiff"] forState:UIControlStateHighlighted];
        [self.player play];
    }
}

// 重写setter方法
- (void)setUrlArr:(NSMutableArray *)urlArr
{
    if (_urlArr != urlArr) {
        [_urlArr release];
        _urlArr = [urlArr retain];
    }
    [self setupUI];
    [self.player play];
    
    if (1 == self.player.rate) {
        [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_pause_hover.tiff"] forState:UIControlStateNormal];
        [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_pause_down.tiff"] forState:UIControlStateHighlighted];
    } else {
        [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_play_hover.tiff"] forState:UIControlStateNormal];
        [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_play_down.tiff"] forState:UIControlStateHighlighted];
    }
}

// 创建播放器
- (void)setupUI
{
    //创建播放器层
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = self.container.bounds;
    [self.container.layer addSublayer:self.playerLayer];
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;//视频填充模式
}

// 重写getter方法 初始化播放器
- (AVPlayer *)player
{
    if (!_player) {
        AVPlayerItem *playerItem = [self getPlayItem:0];
        _player=[AVPlayer playerWithPlayerItem:playerItem];
        // 添加进度监控
        [self addProgressObserver];
        // 添加状态监控
        [self addObserverToPlayerItem:playerItem];
        // 添加消息通知
        [self addNotification];
    }
    return _player;
}

// 根据视频索引取得AVPlayerItem对象
- (AVPlayerItem *)getPlayItem:(int)videoIndex
{
    NSString *urlStr = [self.urlArr objectAtIndex:videoIndex];
    NSURL *url = [NSURL URLWithString:urlStr];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    return playerItem;
}

#pragma mark - 通知
/**
 *  添加播放器通知
 */
-(void)addNotification{
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}
-(void)playbackFinished:(NSNotification *)notification{
    NSLog(@"视频播放完成.");
    // 按钮状态置零
    [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_play_hover.tiff"] forState:UIControlStateNormal];
    [self.playOrPauseB setImage:[UIImage imageNamed:@"large_cover_play_hover.tiff"] forState:UIControlStateHighlighted];
    self.proSlider.value = 0;
}
-(void)removeNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 监控 关联slider
/**
 *  给播放器添加进度更新
 */
-(void)addProgressObserver{
    
    AVPlayerItem *playerItem = self.player.currentItem;
    
    //这里设置每秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current = CMTimeGetSeconds(time);
        float total = CMTimeGetSeconds([playerItem duration]);
//        NSLog(@"当前已经播放%.2fs.",current);
        if (current) {
            self.proSlider.value = current / total;
        }
        int currentTime = (int)current;
        self.timeL.text = [NSString stringWithFormat:@"%02d:%02d", currentTime / 60, currentTime % 60];
    }];
}

/**
 *  给AVPlayerItem添加监控
 *
 *  @param playerItem AVPlayerItem对象
 */
- (void)addObserverToPlayerItem:(AVPlayerItem *)playerItem
{
    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监控网络加载情况属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem
{
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
/**
 *  通过KVO监控播放器状态
 *
 *  @param keyPath 监控属性
 *  @param object  监视器
 *  @param change  状态改变
 *  @param context 上下文
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    AVPlayerItem *playerItem = object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
        if(status == AVPlayerStatusReadyToPlay){
//            NSLog(@"正在播放...，视频总长度;:%.2f",CMTimeGetSeconds(playerItem.duration));
        }
    } else if([keyPath isEqualToString:@"loadedTimeRanges"]){
         NSArray *array = playerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
//        NSLog(@"共缓冲：%.2f",totalBuffer);
        
        self.progressV.progress = totalBuffer / CMTimeGetSeconds(playerItem.duration);
    }
}

/**
 *  切换选集，这里使用按钮的tag代表视频名称
 *
 *  @param sender 点击按钮对象
 */

@end
